const express = require('express');
const multer = require('multer');
const path = require('path');
const scoreController = require('../controllers/scoreController');
const authController = require('../controllers/authController');
const aiModelController = require('../controllers/aiModelController');
const aiAnalysisService = require('../services/aiAnalysisService');
const { Score, Student, StudentAnalysis } = require('../models');

const router = express.Router();

// 配置文件上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, process.env.UPLOAD_DIR || './uploads');
  },
  filename: (req, file, cb) => {
    // 修复中文文件名乱码问题
    // multer 会将文件名编码为 latin1，需要转换回 utf8
    const originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
    file.originalname = originalname;
    
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(originalname));
  }
});

const upload = multer({
  storage,
  limits: {
    fileSize: parseInt(process.env.MAX_FILE_SIZE) || 10 * 1024 * 1024 // 10MB
  }
});

// 认证路由
router.post('/auth/login', authController.login.bind(authController));

// 公开路由（学生查询成绩，不需要认证）
router.get('/public/scores', scoreController.queryScores.bind(scoreController));

// 成绩路由（需要认证）
router.post('/scores/import', 
  authController.verifyToken.bind(authController),
  upload.single('file'), 
  scoreController.importScores.bind(scoreController)
);

router.get('/scores', 
  authController.verifyToken.bind(authController),
  scoreController.queryScores.bind(scoreController)
);

router.get('/import-logs', 
  authController.verifyToken.bind(authController),
  scoreController.getImportLogs.bind(scoreController)
);

router.get('/import-logs/:id/errors', 
  authController.verifyToken.bind(authController),
  scoreController.getImportErrors.bind(scoreController)
);

// AI 模型配置路由（需要认证）
router.get('/ai-models',
  authController.verifyToken.bind(authController),
  aiModelController.getAllModels.bind(aiModelController)
);

router.get('/ai-models/active',
  authController.verifyToken.bind(authController),
  aiModelController.getActiveModel.bind(aiModelController)
);

router.post('/ai-models',
  authController.verifyToken.bind(authController),
  aiModelController.createModel.bind(aiModelController)
);

router.put('/ai-models/:id',
  authController.verifyToken.bind(authController),
  aiModelController.updateModel.bind(aiModelController)
);

router.put('/ai-models/:id/activate',
  authController.verifyToken.bind(authController),
  aiModelController.activateModel.bind(aiModelController)
);

router.delete('/ai-models/:id',
  authController.verifyToken.bind(authController),
  aiModelController.deleteModel.bind(aiModelController)
);

// AI 分析路由 - 流式输出版本（公开，学生可以查看自己的分析）
router.post('/public/analysis/stream', async (req, res) => {
  try {
    const { name, className, forceRefresh } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '请提供学生姓名'
      });
    }
    
    // 设置SSE响应头
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('X-Accel-Buffering', 'no'); // 禁用nginx缓冲
    
    // 查询学生的所有成绩记录
    const scores = await Score.findAll({
      include: [{
        model: Student,
        as: 'student',
        where: { name },
        attributes: ['student_id', 'name', 'class_name']
      }],
      order: [['exam_date', 'DESC']],
      limit: 10
    });
    
    if (scores.length === 0) {
      res.write(`data: ${JSON.stringify({ error: '未找到该学生的成绩记录' })}\n\n`);
      return res.end();
    }
    
    const studentId = scores[0].student.student_id;
    const studentName = scores[0].student.name;
    const studentClassName = scores[0].student.class_name;
    const latestExamDate = scores[0].exam_date;
    
    // 检查缓存
    let cachedAnalysis = await StudentAnalysis.findOne({
      where: { student_id: studentId }
    });
    
    let needRegenerate = !cachedAnalysis || forceRefresh || 
      (cachedAnalysis.last_exam_date && new Date(latestExamDate) > new Date(cachedAnalysis.last_exam_date));
    
    if (!needRegenerate) {
      // 使用缓存，直接返回完整报告
      res.write(`data: ${JSON.stringify({ 
        type: 'cache',
        content: cachedAnalysis.analysis_report,
        cachedAt: cachedAnalysis.updated_at
      })}\n\n`);
      return res.end();
    }
    
    // 准备数据
    const studentData = {
      name: studentName,
      className: studentClassName,
      scores: scores.map(score => ({
        examName: score.exam_name,
        examDate: score.exam_date,
        chinese: score.chinese,
        math: score.math,
        english: score.english,
        physics: score.physics,
        chemistry: score.chemistry,
        biology: score.biology,
        politics: score.politics,
        history: score.history,
        geography: score.geography,
        totalScore: score.total_score,
        schoolRank: score.school_rank
      }))
    };
    
    // 流式生成报告
    let fullReport = '';
    await aiAnalysisService.generateAnalysisReportStream(studentData, (chunk) => {
      fullReport += chunk;
      res.write(`data: ${JSON.stringify({ type: 'chunk', content: chunk })}\n\n`);
    });
    
    // 保存到缓存
    if (cachedAnalysis) {
      await cachedAnalysis.update({
        student_name: studentName,
        class_name: studentClassName,
        analysis_report: fullReport,
        exam_count: scores.length,
        last_exam_date: latestExamDate,
        updated_at: new Date()
      });
    } else {
      await StudentAnalysis.create({
        student_id: studentId,
        student_name: studentName,
        class_name: studentClassName,
        analysis_report: fullReport,
        exam_count: scores.length,
        last_exam_date: latestExamDate
      });
    }
    
    // 发送完成信号
    res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`);
    res.end();
    
  } catch (error) {
    console.error('生成分析报告失败:', error);
    res.write(`data: ${JSON.stringify({ 
      type: 'error', 
      message: error.message || '生成分析报告失败' 
    })}\n\n`);
    res.end();
  }
});

// AI 分析路由（公开，学生可以查看自己的分析）
router.post('/public/analysis', async (req, res) => {
  try {
    const { name, className, forceRefresh } = req.body;
    
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '请提供学生姓名'
      });
    }
    
    // 查询学生的所有成绩记录
    const scores = await Score.findAll({
      include: [{
        model: Student,
        as: 'student',
        where: { name },
        attributes: ['student_id', 'name', 'class_name']
      }],
      order: [['exam_date', 'DESC']],
      limit: 10 // 最多分析最近10次考试
    });
    
    if (scores.length === 0) {
      return res.status(404).json({
        success: false,
        message: '未找到该学生的成绩记录'
      });
    }
    
    const studentId = scores[0].student.student_id;
    const studentName = scores[0].student.name;
    const studentClassName = scores[0].student.class_name;
    const latestExamDate = scores[0].exam_date;
    
    // 检查是否有缓存的分析报告
    let cachedAnalysis = await StudentAnalysis.findOne({
      where: { student_id: studentId }
    });
    
    // 判断是否需要重新生成报告
    let needRegenerate = false;
    
    if (!cachedAnalysis) {
      // 没有缓存，需要生成
      needRegenerate = true;
      console.log(`学生 ${studentName} 没有缓存的分析报告，将生成新报告`);
    } else if (forceRefresh) {
      // 强制刷新
      needRegenerate = true;
      console.log(`学生 ${studentName} 强制刷新分析报告`);
    } else {
      // 检查是否有新的考试成绩
      const cachedExamDate = cachedAnalysis.last_exam_date;
      if (!cachedExamDate || new Date(latestExamDate) > new Date(cachedExamDate)) {
        needRegenerate = true;
        console.log(`学生 ${studentName} 有新的考试成绩，将重新生成报告`);
      } else {
        console.log(`学生 ${studentName} 使用缓存的分析报告`);
      }
    }
    
    let report;
    let fromCache = false;
    
    if (needRegenerate) {
      // 准备数据
      const studentData = {
        name: studentName,
        className: studentClassName,
        scores: scores.map(score => ({
          examName: score.exam_name,
          examDate: score.exam_date,
          chinese: score.chinese,
          math: score.math,
          english: score.english,
          physics: score.physics,
          chemistry: score.chemistry,
          biology: score.biology,
          politics: score.politics,
          history: score.history,
          geography: score.geography,
          totalScore: score.total_score,
          schoolRank: score.school_rank
        }))
      };
      
      // 生成新的分析报告
      report = await aiAnalysisService.generateAnalysisReport(studentData);
      
      // 保存或更新缓存
      if (cachedAnalysis) {
        // 更新现有记录
        await cachedAnalysis.update({
          student_name: studentName,
          class_name: studentClassName,
          analysis_report: report,
          exam_count: scores.length,
          last_exam_date: latestExamDate,
          updated_at: new Date()
        });
        console.log(`已更新学生 ${studentName} 的分析报告缓存`);
      } else {
        // 创建新记录
        await StudentAnalysis.create({
          student_id: studentId,
          student_name: studentName,
          class_name: studentClassName,
          analysis_report: report,
          exam_count: scores.length,
          last_exam_date: latestExamDate
        });
        console.log(`已创建学生 ${studentName} 的分析报告缓存`);
      }
      
      fromCache = false;
    } else {
      // 使用缓存的报告
      report = cachedAnalysis.analysis_report;
      fromCache = true;
    }
    
    res.json({
      success: true,
      data: {
        report,
        studentName,
        className: studentClassName,
        examCount: scores.length,
        fromCache,
        cachedAt: cachedAnalysis ? cachedAnalysis.updated_at : null
      }
    });
  } catch (error) {
    console.error('生成分析报告失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '生成分析报告失败'
    });
  }
});

// 更新分析报告（手动编辑）
router.post('/public/analysis/update', async (req, res) => {
  try {
    const { name, className, report } = req.body;
    
    if (!name || !report) {
      return res.status(400).json({
        success: false,
        message: '请提供学生姓名和报告内容'
      });
    }
    
    // 查询学生信息
    const student = await Student.findOne({
      where: { name }
    });
    
    if (!student) {
      return res.status(404).json({
        success: false,
        message: '未找到该学生'
      });
    }
    
    // 更新或创建分析报告
    const [analysis, created] = await StudentAnalysis.findOrCreate({
      where: { student_id: student.student_id },
      defaults: {
        student_id: student.student_id,
        student_name: name,
        class_name: className || student.class_name,
        analysis_report: report,
        exam_count: 0,
        last_exam_date: null
      }
    });
    
    if (!created) {
      await analysis.update({
        analysis_report: report,
        updated_at: new Date()
      });
    }
    
    console.log(`学生 ${name} 的分析报告已手动更新`);
    
    res.json({
      success: true,
      message: '报告保存成功'
    });
  } catch (error) {
    console.error('保存报告失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '保存报告失败'
    });
  }
});

module.exports = router;
